<template>
  <div class="app-container">
    <!-- 查询表单 -->
    <!--查询表单-->
    <el-form :inline="true" class="demo-form-inline">
      <el-form-item>
        <el-input v-model="searchObj.roleName" placeholder="角色名称"/>
      </el-form-item>
      <el-form-item>
        <el-input v-model="searchObj.roleKey" placeholder="角色编码"/>
      </el-form-item>
      <el-form-item>
        <el-select v-model="searchObj.state" clearable placeholder="状态">
          <el-option :value="1" label="启用"/>
          <el-option :value="0" label="停用"/>
        </el-select>
      </el-form-item>
      <el-form-item label="创建时间">
        <el-date-picker
          v-model="searchObj.begin"
          type="datetime"
          placeholder="选择开始时间"
          value-format="yyyy-MM-dd HH:mm:ss"
          default-time="00:00:00"
        />
      </el-form-item>
      <el-form-item>
        <el-date-picker
          v-model="searchObj.end"
          type="datetime"
          placeholder="选择截止时间"
          value-format="yyyy-MM-dd HH:mm:ss"
          default-time="00:00:00"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" @click="fetchData()">查询</el-button>
        <el-button type="default" @click="resetData()">清空</el-button>
      </el-form-item>

    </el-form>

    <!-- 工具条 -->
    <div>
      <el-button type="primary" size="mini" icon="el-icon-plus" @click="addRole()" v-if="hasPerm('system:role:add')">添加</el-button>
      <el-button type="danger" size="mini" icon="el-icon-delete" @click="removeRows()" v-if="hasPerm('system:role:remove')">批量删除</el-button>
    </div>

    <!-- 角色列表 -->
    <el-table
      v-loading="listLoading"
      :data="list"
      stripe
      style="width: 100%"
      @selection-change="handleSelectionChange">

      <el-table-column
        type="selection"
        width="55" />

      <el-table-column
        label="序号"
        width="70"
        align="center">
        <template slot-scope="scope">
          {{ (page - 1) * limit + scope.$index + 1 }}
        </template>
      </el-table-column>

      <el-table-column prop="roleName" label="角色名称" align="center" width="160"/>

      <el-table-column prop="roleKey" label="角色编码" align="center" width="160"/>

      <el-table-column label="状态" align="center" width="200">
        <!-- <template slot-scope="scope">
          {{ scope.row.state===1?'启用':'停用' }}
        </template> -->
        <template slot-scope="scope">
          <el-switch
            v-model="scope.row.state"
            :active-value="1"
            :inactive-value="0"
            @change="handleStatusChange(scope.row)"
          ></el-switch>
        </template>
      </el-table-column> 

      <el-table-column prop="gmtCreate" label="创建时间" align="center" width="200"/>


      <el-table-column label="操作"  align="center">
        <template slot-scope="scope">
          

          <el-button type="primary" size="mini" icon="el-icon-edit" @click="updateRole(scope.row.id)"  v-if="hasPerm('system:role:update')">编辑</el-button>

          <el-button type="primary" size="mini" icon="el-icon-s-custom" @click="authRole(scope.row.id)" v-if="hasPerm('system:role:auth')">授权</el-button>

          <el-button type="danger" size="mini" icon="el-icon-delete" @click="removeDataById(scope.row.id)" v-if="hasPerm('system:role:remove')">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页组件 -->
    <el-pagination
      :current-page="page"
      :total="total"
      :page-size="limit"
      :page-sizes="[5, 10, 20, 30, 40, 50, 100]"
      style="padding: 30px 0; text-align: center;"
      layout="sizes, prev, pager, next, jumper, ->, total, slot"
      @current-change="fetchData"
      @size-change="changeSize"
    />

    <!-- 添加或修改角色配置对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="form.roleName" placeholder="请输入角色名称" />
        </el-form-item>
        <el-form-item label="角色编码" prop="roleKey">
          <el-input v-model="form.roleKey" placeholder="请输入角色编码" />
        </el-form-item>
        <el-form-item label="状态" prop="state">
          <el-radio-group v-model="form.state">
            <el-radio :label='1'>启用</el-radio>
            <el-radio :label='0'>停用</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button :disabled="saveBtn" type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 分配角色数据权限对话框 -->
    <el-dialog :title="title" :visible.sync="openMenuData" width="30%" append-to-body>
      <el-form >
        <div>
          <el-tree
            ref="tree"
            class="tree-border"
            :data="menus"
            :default-checked-keys="menuIds"
            accordion
            show-checkbox
            highlight-current
            node-key="id"
            empty-text="加载中，请稍后"
            :props="defaultProps"
          ></el-tree>
        </div>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button :disabled="saveRoleMenuBtn" type="primary" @click="saveRoleMenu">确 定</el-button>
        <el-button @click="handleClose">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import roleApi from '@/api/system/role'
import menuApi from '@/api/system/menu'

export default {
  data() {
    return {
      listLoading: true, // 数据是否正在加载
      list: null, // 讲师列表
      total: 0, // 数据库中的总记录数
      page: 1, // 默认页码
      limit: 10, // 每页记录数
      searchObj: {}, // 查询表单对象
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 表单参数
      form: {
        state: 1
      },
      multipleSelection: [], // 批量选择中选择的记录列表
      // 表单校验
      rules: {
        roleName: [
          { required: true, message: "角色名称不能为空", trigger: "blur" }
        ],
        roleKey: [
          { required: true, message: "角色编码不能为空", trigger: "blur" }
        ],
        state: [
          { required: true, message: "状态不能为空", trigger: "blur" }
        ]
      },
      saveBtn: false,
      // 授权
      openMenuData: false,
      menus: [],
      roleId: 0,
      menuIds: [],
      defaultProps: {
        children: "children",
        label: "label"
      },
      saveRoleMenuBtn: false
    }
  },

  // 生命周期函数：内存准备完毕，页面尚未渲染
  created() {
    console.log('list created......')
    this.fetchData()
  },

  // 生命周期函数：内存准备完毕，页面渲染成功
  mounted() {
    console.log('list mounted......')
  },

  methods: {
    // 表单初始化
    init() {
      debugger
      if (this.$route.params && this.$route.params.id) {
        const id = this.$route.params.id
        this.fetchDataById(id)
      } else {
        // 对象拓展运算符：拷贝对象，而不是赋值对象的引用
        this.role = { ...defaultForm }
      }
    },
    // 当页码发生改变的时候
    changeSize(size) {
      this.limit = size
      this.fetchData(1)
    },

    addRole(){
      this.reset();
      this.open = true;
      this.title = "添加角色";
    },
    updateRole(id){
      this.reset();
      roleApi.getRoleById(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改角色";
      });

    },
    // 授权
    authRole(id){
      //console.log(id)
      this.openMenuData = true

      this.getRoleMenuTreeselect(id);
      this.roleId = id
    },
    getRoleMenuTreeselect(id){
      return menuApi.roleMenuTree(id).then(response => {
        let menuOptions = []
        let menus = response.data.menus;
        for (var i in menus) {
          menuOptions.push(menus[i])
        }
        this.menus = menuOptions
        
        this.menuIds = response.data.checkedKeys
      
        // 过滤非全选的父级菜单
        this.menus.forEach(item => {
          if (this.setChecked(item)) {
            this.menuIds.splice(this.menuIds.indexOf(item.id), 1)
          }
        })
      });
    },
    setChecked(row) {
      if (this.menuIds.indexOf(row.id) !== -1) {
        let int = 0;
        row.children.forEach(item => {
          if (this.setChecked(item)) {
            this.menuIds.splice(this.menuIds.indexOf(item.id), 1)
          }
          if (this.menuIds.indexOf(item.id) !== -1) {
            int += 1
          }
        })
        if (int < row.children.length) {
          return true
        } else {
          return false
        }
      }
    },
    // 提交表单
    submitForm(){
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.saveBtn = true
          let form = this.form
          // 修改
          if (form.id != undefined) {
            console.log(form)
            this.updateData(form)
          } else {// 新增
            this.saveData(form)
          }
        }
      })
    },
    // 添加
    saveData(form){
      roleApi.addRole(form).then(response =>{
        if(response.code ===200) {
          this.$message({
          type: 'success',
          message: '添加成功'
        })
        this.open = false;
        this.saveBtn = false
        this.fetchData();
        }
      });
    },
    // 修改
    updateData(form){
      roleApi.updateRole(form).then(response =>{
        if(response.code ===200) {
          this.$message({
          type: 'success',
          message: '修改成功'
        })
        this.open = false;
        this.saveBtn = false
        this.fetchData();
        }
      });
    },
    // 根据id删除
    removeDataById(id){
      this.$confirm('此操作将永久删除该记录, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => { // promise
        // 点击确定，远程调用ajax
        return roleApi.removeById(id)
      }).then((response) => {
        this.fetchData(this.page)
        if (response.code === 200) {
          this.$message({
            type: 'success',
            message: '删除成功!'
          })
        }
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    removeRows(){
      if (this.multipleSelection.length === 0) {
        this.$message({
          type: 'warning',
          message: '请选择要删除的记录!'
        })
        return
      }

      this.$confirm('此操作将永久删除该记录, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => { // promise
        // 点击确定，远程调用ajax
        // 遍历selection，将id取出放入id列表
        var idList = []
        this.multipleSelection.forEach(item => {
          idList.push(item.id)
        // console.log(idList)
        })
        // 调用api
        return roleApi.removeBatchs(idList)
      }).then((response) => {
        this.fetchData(this.page)
        if (response.code === 200) {
          this.$message({
            type: 'success',
            message: '删除成功!'
          })
        }
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    cancel(){
      this.open = false;
      this.reset();
    },
    // 授权
    saveRoleMenu(){
      const role = { roleId: this.roleId, menuId: [] }
      // 获取目前被选中的节点的 key 所组成的数组 与 获取半选中的节点的 key 所组成的数组
      // 目前被选中的菜单节点
      let checkedKeys = this.$refs.tree.getCheckedKeys();
      // 半选中的菜单节点
      let halfCheckedKeys = this.$refs.tree.getHalfCheckedKeys();
      checkedKeys.unshift.apply(checkedKeys, halfCheckedKeys);
      let unique= [...new Set(checkedKeys)];
      //console.log(unique);
      unique.forEach(function(data, index) {
        role.menuId.push(data)
      })
      //console.log(role)
      // 保存角色信息
      roleApi.saveRoleMenu(role).then(response =>{
        // console.log(role)
        this.saveRoleMenuBtn=true
        if (response.code === 200){
          this.$message({
            type: 'success',
            message: '保存成功!'
          })
          this.saveRoleMenuBtn=false
          this.handleClose()
        } else {
          this.$message({
            type: 'warning',
            message: '保存失败!'
          })
        }
      })
      
    },
    handleClose(){
      this.openMenuData = false
      this.menus = []
      this.menuIds = []
    },

    // 表单重置
    reset() {
      this.form = {};
    },

    // 加载讲师列表数据
    fetchData(page = 1) {
      console.log('翻页。。。' + page)
      // 异步获取远程数据（ajax）
      this.page = page

      roleApi.roleList(this.page, this.limit, this.searchObj).then(
        response => {
          this.list = response.data.records
          this.total = response.data.total

          // 数据加载并绑定成功
          this.listLoading = false
        }
      )
    },

    // 重置查询表单
    resetData() {
      console.log('重置查询表单')
      this.searchObj = {}
      this.fetchData()
    },

    // 当表格复选框选项发生变化的时候触发
    handleSelectionChange(selection) {
      console.log('handleSelectionChange......')
      console.log(selection)
      this.multipleSelection = selection
    },
    // 修改角色状态
    handleStatusChange(row) {
      console.log(row.state)
      let text = row.state === 1 ? "启用" : "停用";
      this.$confirm('确认要' + text + '“' + row.roleName + '”角色吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => { // promise
        // 点击确定，远程调用ajax
        // 遍历selection，将id取出放入id列表
        return roleApi.changeRoleState(row.id, row.state)
      }).then(() => {
          this.fetchData(this.page)
          this.$message({
            type: 'success',
            message: text + "成功"
          })
        }).catch(function() {
          row.state = row.state === "0" ? "1" : "0";
      });
    }
  }
}
</script>

